import json
import os

from django.shortcuts import render, redirect, reverse
from django.http import HttpResponse as response
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.core import serializers
from django.db import transaction
from django.core.paginator import Paginator

from myapp.models import *


# Create your views here.
def index(request):
    return render(request, 'index.html')


@csrf_exempt
def test01(request):
    dic = {}
    if request.method == 'GET':
        dic['message'] = 0
        return response(json.dumps(dic))
    else:
        dic['message'] = '方法错误'
        return response(json.dumps(dic))


# get方式,传统url问号？传参
@csrf_exempt
def test02(request):
    username = request.GET.get('username')
    number = request.GET.get('number')
    return response('你好%s,欢迎使用Django!,你输入的数字为%s' % (username, number))


# post formdata
@csrf_exempt
def test03(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        return response('账号%s,密码%s' % (username, password))
    else:
        return response('请求失败')


# 实现重定向
@csrf_exempt
def start(request):
    # return response('开始重定向')
    # return redirect('/pms_sa/end')
    return redirect(reverse('end'))


@csrf_exempt
def end(request):
    return response('重定向完成')


@csrf_exempt
def test_add(request):
    try:
        id = request.POST.get('id')
        username = request.POST.get('username')
        address = request.POST.get('address')
        birthday = request.POST.get('birthday')
        salary = request.POST.get('salary')

        user_db = TUser.objects.filter(pk=id)
        # if user_db.__len__() != 0:
        if user_db.exists():
            return response("新增用户失败,已存在该用户")
        else:
            with transaction.atomic():
                user = TUser(id=id, username=username, address=address, birthday=birthday, salary=salary)
                user.save()
    except Exception as e:
        return response("新增用户失败,出现错误:%s" % str(e))
    return response("新增用户成功")


@csrf_exempt
def test_update(request):
    try:
        id = request.POST.get('id')
        username = request.POST.get('username')
        address = request.POST.get('address')
        birthday = request.POST.get('birthday')
        salary = request.POST.get('salary')

        user_db = TUser.objects.filter(pk=id)
        if not user_db.exists():
            return response("修改用户失败,不存在该用户")
        else:
            with transaction.atomic():
                user = TUser(id=id, username=username, address=address, birthday=birthday, salary=salary)
                user.save()
    except Exception as e:
        return response("修改用户失败,出现错误:%s" % str(e))
    return response("修改用户成功")


def test_delete(request):
    try:
        id = request.GET.get('id')
        user = TUser.objects.filter(pk=id)
        if not user.exists():
            return response("删除用户失败,无该用户")
        else:
            with transaction.atomic():
                print(5 / 0)
                user.delete()
    except Exception as e:
        return response("删除用户失败,出现错误:%s" % str(e))
    return response("删除用户成功")


def test_find_all(request):
    result = {"message": 'success', "code": '0', "data": [], "rows": 0}  # 结果集封装json
    users = TUser.objects.all().order_by('salary')
    # result["data"] = json.loads(serializers.serialize('json', users)) #先json序列化通过json.loads()转化为python数据类型
    result["data"] = list(users.values())  # 为了只获取fields,使用users.values()返回ValuesQuerySet对象再转化为list
    result["rows"] = users.count()
    return JsonResponse(result, json_dumps_params={'ensure_ascii': False})  # 处理中文编码错误


# 文件上传
def upload_file(request):
    if request.method == "GET":
        return render(request, "upload.html")
    elif request.method == "POST":
        file = request.FILES.get("file", None)
        if not file:
            return response("请上传文件")
        f = open(os.path.join("C:\\Users\\53470\\Desktop", file.name), 'wb+')  # os.path.join拼接文件路径
        # try:
        #     for chunk in file.chunks():  # 按块返回文件，通过在for循环中进行迭代，可以将大文件按块写入到服务器中
        #         f.write(chunk)
        # except Exception as e:
        #     return response("上传文件失败,出现错误:%s" % str(e))
        # finally:
        #     f.close()

        # 改用with,简化try/finally
        with open(os.path.join("C:\\Users\\53470\\Desktop", file.name), 'wb+') as f:
            for chunk in file.chunks():
                #print(5 / 0)
                f.write(chunk)

        return response("上传文件成功")


def getUnits(request):
    return getList(request, SaUnit)


def getSystems(request):
    return getList(request, SaSystem)


def getDomains(request):
    return getList(request, SaDomain)


def getList(request, model):
    page = int(request.GET.get('page'))
    pageSize = int(request.GET.get('pageSize'))
    res = {}
    querySets = model.objects.all()
    ptr = Paginator(querySets.values(), pageSize)
    data = ptr.page(page)
    res["list"] = list(data)
    res["page"] = page
    res["rows"] = ptr.count
    res["pages"] = ptr.num_pages
    return JsonResponse(res, json_dumps_params={'ensure_ascii': False})
